// 存档模块
import { deleteDB, openDB } from 'idb'
import { World } from './type'

const dbName = 'factories',
	storeName = 'saves'

// IndexedDB
let db = await openDB(dbName, 1, {
	upgrade(db, oldVer) {
		if (oldVer < 1)
			db.createObjectStore(storeName)
	}
})

/** 当前存档 */
export let world: World

/** 清除存档数据 */
export function clearData(delDB = true) {
	if (delDB) {
		db.close()
		return deleteDB(dbName, {
			blocked() {
				console.log(dbName + ': db is in use')
			},
		})
	}
	return db.clear(storeName)
}

/**
 * 读取存档
 * @param name 存档名称
 * @returns 存档数据
 */
export async function load(name: string) {
	world = await db.get(storeName, name)
}

/** 获取存档列表 */
export function list(limit = 10) {
	return db.getAll(storeName, null, limit).catch(() => [])
}

/**
 * 保存存档
 * @param name 存档名称
 */
export async function save(item = world) {
	const { save } = await import('./game')
	if (save) {
		item.data.length = 0
		save()
	}
	const data = {
		...item,
	}
	if (item.map) {
		// 保存地图
		const size = item.mapSize ** 2
		data.map = new Uint8Array(size * 2)
		for (let i = 0; i < size; i++) {
			data.map[i << 1] = item.map[i * 4 + 2]
			data.map[i << 1 | 1] = item.map[i * 4 + 3]
		}
	}
	// 更新时间
	data.updated = +new Date
	return db.put(storeName, data, item.name)
}

/**
 * 删除存档
 * @param name 存档名称
 */
export function del(name: string) {
	return db.delete(storeName, name)
}
